package kp.rpc.bootstrap;

import kp.rpc.RpcApplication;
import kp.rpc.config.RegistryConfig;
import kp.rpc.config.RpcConfig;
import kp.rpc.model.ServiceMetaInfo;
import kp.rpc.model.ServiceRegisterInfo;
import kp.rpc.registry.LocalRegistry;
import kp.rpc.registry.Registry;
import kp.rpc.registry.factory.RegistryFactory;
import kp.rpc.server.tcp.VertxTcpServer;

import java.util.List;
import java.util.Optional;

/**
 * 初始化服务提供者
 */
public class ProviderBootStrap {
    public static void init(List<ServiceRegisterInfo<?>> serviceRegisterInfoList, boolean open) {
        //全局配置
        final RpcConfig rpcConfig = RpcApplication.getRpcConfig();
        //注册服务
        Optional.ofNullable(serviceRegisterInfoList).ifPresent(list -> {
            list.forEach(item -> {
                String serviceName = item.getServiceName();
                //本地注册
                LocalRegistry.register(serviceName, item.getImplClass());
                //注册服务到注册中心
                RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
                Registry registry = RegistryFactory.getRegistry(registryConfig.getRegisterType());
                ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
                serviceMetaInfo.setServiceName(serviceName);
                serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
                serviceMetaInfo.setServicePort(rpcConfig.getServerPort());
                try {
                    registry.register(serviceMetaInfo);
                } catch (Exception e) {
                    throw new RuntimeException(serviceName + "服务注册失败！", e);
                }
            });
        });
        if (open) {
            VertxTcpServer vertxTcpServer = new VertxTcpServer();
            vertxTcpServer.doStart(rpcConfig.getServerPort());
        }
    }
}
